# 1 - Import library
from pygame.locals import *
import pygame
from math import * 
from random import *
import time
# 2 - Initialize the game
pygame.init()
screen_width,screen_height = (640,480)
ck = pygame.display.set_mode((screen_width,screen_height))
key_tag = [True,True,True,True]
dudepos = [100, 100]
acc = [0, 0]
arrows = []
startTimer = 0
badtimer = 100
badtimer1 = 0
badguys = [[640, 100]]
healthvalue = 194
timer = randint(10,80)
clock = pygame.time.Clock()
start_ck = pygame.Surface(ck.get_size())    
start_ck2 = pygame.Surface(ck.get_size()) 
start_ck = start_ck.convert()
start_ck2 = start_ck2.convert()
# 3 - Load images
dude = pygame.image.load('123456789/images/dude.png')
grass = pygame.image.load('123456789/images/grass.png')
castle = pygame.image.load('123456789/images/兔子窝.png')
bullet = pygame.image.load('123456789/images/bullet.png')
beijing = pygame.image.load('123456789/images/111.png')
#加载獾图片
badguy1 = pygame.image.load('123456789/images/badguy.png')
badguy2 = pygame.image.load('123456789/images/badguy2.png')
badguy3 = pygame.image.load('123456789/images/badguy3.png')
badguy4 = pygame.image.load('123456789/images/badguy4.png')
badguy = [badguy1,badguy2,badguy3,badguy4]
n = 0
s = 0
#加载健康图片
redbar = pygame.image.load('123456789/images/healthbar.png')
greenbar = pygame.image.load('123456789/images/health.png')

#加载输赢图片
win = pygame.image.load('123456789/images/youwin.png')
lose = pygame.image.load('123456789/images/gameover.png')
beginner = pygame.image.load('123456789/images/再试开始.png')
shibai = pygame.image.load('123456789/images/失败.png')

#加载菜单图片
start = pygame.image.load('123456789/images/开始游戏.png')
jd =pygame.image.load('123456789/images/jd.png')
kn = pygame.image.load('123456789/images/kn.png')


# 3.1 加载声音
hit = pygame.mixer.Sound('123456789/audio/shoot.wav')
enemy = pygame.mixer.Sound('123456789/audio/enemy.wav')
shoot = pygame.mixer.Sound('123456789/audio/shoot.wav')
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)


fontColor=(52, 53, 44)
musicOn = True
levelMode =1
moveSpeed = 10
maxScore=[0,0]
curScore =0;
running = 1
exitcode = 0

i1 = pygame.image.load("123456789/images/开始游戏.png")
i1.convert()
i11 = pygame.image.load("123456789/images/开始游戏.png")
i11.convert()

i2 = pygame.image.load("123456789/images/结束游戏.png")
i2.convert()
i21 = pygame.image.load("123456789/images/结束游戏.png")
i21.convert()

i3 = pygame.image.load("123456789/images/grass.png")
i3.convert()
i31 = pygame.image.load("123456789/images/grass.png")
i31.convert()

bg = pygame.image.load("123456789/images/grass.png")
bg.convert()

i4 = pygame.image.load('123456789/images/再试开始.png')
i4.convert()
i44 = pygame.image.load('123456789/images/再试开始.png')
i44.convert()

i5 = pygame.image.load('123456789/images/失败.png')
i5.convert()
i55 = pygame.image.load('123456789/images/失败.png')
i55.convert()
def print_text(screen, font, x, y, text, color=(0, 0, 0)):

     
    imgText = font.render(text, True, color)
    screen.blit(imgText, (x, y))
def run():

    while True:
        startMenu()
        startGame()
        pygame.display.flip()
def startMenu():
    menuPos = []
    ck.fill(0)

    ck.blit(beijing, (0, 0))
    if not pygame.font.get_init():
        pygame.font.init()
  
    size =start.get_size()  
    x = 850/2- size[0]/2 
    y = 1000/2 -size[1]-15
    ck.blit(start,(x,y)) 
    menuPos.append([x-3,y-3,size[0]+6,size[1]+6]) 


    x = 640 / 2 - size[0] / 2
    y = 480 / 2+5
    menuPos.append([x - 3, y - 3, size[0] + 6, size[1] + 6])
    pygame.display.flip()
    screenCopy = ck.copy()
    while True:
        ck.blit(screenCopy,(0,0))
        for event in pygame.event.get():
            if event.type == MOUSEBUTTONDOWN : 
                if event.button == 1: 
                    pos = event.pos
                    if checkRect(pos,menuPos[0]): #检测是否点击 开始菜单
                        return level()
                    elif checkRect(pos,menuPos[1]): #检测是否 点击 设置
                        settings()
                        pygame.display.set_caption("游戏开始")


        pygame.display.flip()


def checkRect(pos,rect):
    if(pos[0]<rect[0] or pos[1] < rect[1] or pos[0]>rect[0]+rect[2] or pos[1]>rect[1]+rect[3]):
        return False
    return True
#关卡界面
def level():
    global levelMode,moveSpeed
    menuPos = []
    ck.fill(0)
    ck.blit(beijing, (0, 0))
    if not pygame.font.get_init():
        pygame.font.init()  
    size = jd.get_size()  
    x = 850 / 2 - size[0] / 2  
    y = 900 / 2 - size[1] - 15
    ck.blit(jd, (x, y))  
    menuPos.append([x - 3, y - 3, size[0] + 6, size[1] + 6])  

    
    size = kn.get_size()  
    x = 850 / 2 - size[0] / 2 
    y = 670 / 2  + 15
    ck.blit(kn, (x, y))  
    menuPos.append([x - 3, y - 3, size[0] + 6, size[1] + 6])  

    while True:
        for event in pygame.event.get(): #获取事件
            if event.type == MOUSEBUTTONDOWN : #判断是否是鼠标事件
                if event.button == 1: #判断是左键
                    pos = event.pos
                    if checkRect(pos,menuPos[0]): #检测是否点击 简单模式
                        levelMode =0
                        moveSpeed = 3
                        return levelMode
                    elif checkRect(pos,menuPos[1]): #检测是否 点击困难模式
                        levelMode = 1
                        moveSpeed = 7
                        return levelMode
        pygame.display.flip()

#结束界面
def gameOver():
    if not pygame.font.get_init():
        pygame.font.init()
    menuPos=[]
    font = pygame.font.SysFont("simsunnsimsun", 24)  
    mode = font.render("最高得分：%d" % maxScore[levelMode], True, fontColor)  
    size = mode.get_size()  
    x = 640 / 2 - size[0] / 2  
    y = 160 - size[1] - 15
    screen.blit(mode, (x, y))  

    mode = font.render("当前得分：%d" % curScore , True, fontColor)  
    size = mode.get_size()  
    x = 640 / 2 - size[0] / 2  
    y = y+size[1] +30
    screen.blit(mode, (x, y))  

    start = font.render("继续游戏", True, fontColor)  
    size = start.get_size()  
    x = 130
    y = 420
    screen.blit(start, (x, y))
    menuPos.append([x - 3, y - 3, size[0] + 6, size[1] + 6])
    pygame.draw.rect(screen, (0, 0, 0), menuPos[0], 2)

    start = font.render("返回菜单", True, fontColor)
    size = start.get_size()
    x = 350
    y = 420
    screen.blit(start, (x, y))
    menuPos.append([x - 3, y - 3, size[0] + 6, size[1] + 6])
    pygame.draw.rect(screen, (0, 0, 0), menuPos[1], 2)

    while True:
        for event in pygame.event.get():  # 获取事件
            if event.type == MOUSEBUTTONDOWN:  # 判断是否是鼠标事件
                if event.button == 1:  # 判断是左键
                    pos = event.pos
                    if checkRect(pos, menuPos[0]):  # 检测是否点击 继续游戏
                        return 0
                    elif checkRect(pos, menuPos[1]):  # 检测是否 返回
                        return 1
                    
        pygame.display.flip()


    #循环画上背景
    screen.blit(beijing, (0, 0))
    if not pygame.font.get_init():
        pygame.font.init()
    ##font = pygame.font.SysFont("simsunnsimsun", 36)  # 创建字体
    ##mode = font.render("继续游戏", True, fontColor)  # type:pygame.Surface #创建文本
    size = jixuyouxi.get_size()  # 获取文本大小
    x = 640 / 2 - size[0] / 2  # 计算 位置
    y = 480 / 2 - size[1] - 15
    screen.blit(jixuyouxi, (x, y))  # 绘制文本
    menuPos.append([x - 3, y - 3, size[0] + 6, size[1] + 6])  # 保存开始菜单具举行坐标
    ##pygame.draw.rect(screen, (0, 0, 0), menuPos[1], 2)  # 绘制矩形

    
    size = fh.get_size()  # 获取文本大小
    x = 640 / 2 - size[0] / 2 # 计算 位置
    y = 480 / 2  + 15
    screen.blit(fh, (x, y))  # 绘制文本
    menuPos.append([x - 3, y - 3, size[0] + 6, size[1] + 6])  # 保存开始菜单具举行坐标
    ##pygame.draw.rect(screen, (0, 0, 0), menuPos[1], 2)  # 绘制矩形
    

    while True:
        for event in pygame.event.get(): #获取事件
            if event.type == MOUSEBUTTONDOWN : #判断是否是鼠标事件
                if event.button == 1: #判断是左键
                    pos = event.pos
                    if checkRect(pos,menuPos[0]): #检测是否点击 继续游戏
                        return 0
                    elif checkRect(pos,menuPos[1]): #检测是否 返回
                        return 1
                    pygame.display.set_caption("继续游戏")
                    settings()
                    pygame.display.set_caption("返回游戏")

        pygame.display.flip()


def init():
    global healthvalue, running, screen, maxScore, exitcode, keys, playerpos, acc, arrows, startTimer, badtimer, badtimer1, badguys, curScore, accuracy
    keys = [False, False, False, False]
    playerpos = [100, 100]
    acc = [0, 0]
    arrows = []
    healthvalue = 194
    startTimer = pygame.time.get_ticks()
    badtimer = 100
    badtimer1 = 0
    badguys = [[640, 100]]
    healthvalue = 194
    curScore = 0;
    running = 1
    exitcode = 0
    
def startGame():
    
    分数 = 0
    n = 0
    s = 0
    global timer,healthvalue,running,screen,maxScore,exitcode,keys,playerpos,acc,arrows,startTimer,badtimer,badtimer1,badguys,curScore,accuracy
    menuPos=[(552,3,53,30)]
    starFlag = True
    init()
    #显示
    while running:
        timer -= 1
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                exit(0)
            elif event.type == KEYDOWN:
                 if event.key == K_w:
                    key_tag[0] = False
                 elif event.key == K_a:
                    key_tag[1] = False
                 elif event.key == K_s:
                    key_tag[2] = False
                 elif event.key == K_d:
                    key_tag[3] = False
                    
            elif event.type == KEYUP:
                 if event.key == K_w:
                    key_tag[0] = True
                 elif event.key == K_a:
                    key_tag[1] = True
                 elif event.key == K_s:
                    key_tag[2] = True
                 elif event.key == K_d:
                    key_tag[3] = True

            elif event.type == MOUSEBUTTONDOWN:
                x1 = dudepos[0] + dude.get_width()/2 #兔子中心点
                y1 = dudepos[1] + dude.get_height()/2
                pos_mouse = pygame.mouse.get_pos()
                
                x2_b = pygame.mouse.get_pos()[0]#鼠标
                y2_b = pygame.mouse.get_pos()[1]
                
                angle = atan2(y2_b-y1,x2_b-x1)#弧度值
                arrows.append([angle,x1,y1])
                shoot.play()
                acc[1] += 1


                
        step = 2
        if key_tag[0] == False:
            dudepos[1] -= step
        elif key_tag[1] == False:
            dudepos[0] -= step
        elif key_tag[2] == False:
            dudepos[1] += step
        elif key_tag[3] == False:
            dudepos[0] += step

        ck.fill(0)
        #草坪
        ck.blit(dude,dudepos)
        if screen_height % grass.get_height() == 0:
            h_grass = screen_height // grass.get_height()
        else:
            h_grass = screen_height // grass.get_height() + 1

        if screen_width % grass.get_width() == 0:
            w_grass = screen_width // grass.get_width()
        else:
            w_grass = screen_width // grass.get_width() + 1

        for j in range(h_grass):
            for i in range(w_grass):
              ck.blit(grass,(i * grass.get_width(),j * grass.get_height()))

        h_castle = castle.get_height()
        #兔子窝
        for i in range(4):
            ck.blit(castle,(0,i*h_castle+30))

        x1 = dudepos[0] + dude.get_width()/2 #兔子中心点
        y1 = dudepos[1] + dude.get_height()/2
        
        x2 = pygame.mouse.get_pos()[0]#鼠标
        y2 = pygame.mouse.get_pos()[1]
        
        angle_1 = atan2(y2-y1,x2-x1)#弧度值
        angle_2 = 360 * angle_1 / (2 * pi)
        
        duderot = pygame.transform.rotate(dude,-angle_2)
        
        x_duderot = x1 - duderot.get_width()/2
        y_duderot = y1 - duderot.get_height()/2
        
        dudeposf = (x_duderot,y_duderot)

            
        #兔子
        ck.blit(duderot,dudeposf)

        #鼠标
        step_b = 5
        removed_arrows = []
        for arrow in arrows:
            arrow[1] += step_b*cos(arrow[0])
            arrow[2] += step_b*sin(arrow[0])
            if (arrow[1] > screen_width or arrow[2] > screen_height or
                arrow[1] < -bullet.get_width() or arrow[2] < -bullet.get_height()):
                arrows.remove(arrow)
            

        



        if timer == 0:
            x_badguy = screen_width
            y_badguy = randint(0,screen_height)
            badguys.append([x_badguy,y_badguy])
            timer = randint(10,80)
            
            
            
        vel_guy = 3
        removed_badguys = []
        for guy in badguys:
            guy[0] -= vel_guy
            if guy[0] < castle.get_width():
                removed_badguys.append(guy)
                s += 3
            else:
                for arrow in arrows:
                    guyrect = badguy[n%4].get_rect()
                    guyrect.left = guy[0]
                    guyrect.top = guy[1]
                    

                    arrowrect = bullet.get_rect()
                    arrowrect.left = arrow[1]
                    arrowrect.top = arrow[2]

                    if guyrect.colliderect(arrowrect):
                        removed_arrows.append(arrow)
                        removed_badguys.append(guy)
                        s -= 1
                        acc[0] += 1
                        分数+=1
                    if s < 0:
                        s += 1
                    elif s >194:
                        s -= 1
                    
        

        for guy in removed_badguys:
            badguys.remove(guy)
            
            
        step_badguy = 3
        for guy in badguys:
            guy[0] -= step_badguy


        for guy in badguys:
            ck.blit(badguy[n%4],(guy[0],guy[1]))

        for arrow in removed_arrows:
            arrows.remove(arrow)


        for arrow in arrows:
            
           bulletrot = pygame.transform.rotate(bullet,-arrow[0] * 360/(2*pi))
           ck.blit(bulletrot,(arrow[1],arrow[2]))

        
        n += 1

       

        #生命条
        ck.blit(redbar,(230,0))
        n_greenbar = redbar.get_width()//greenbar.get_width()
        left_grennbar = n_greenbar - s
        for i in range(left_grennbar):
            ck.blit(greenbar,(230+i*greenbar.get_width(),3))

        #倒计时
        total_time = 0.30#分钟
        taken_time = pygame.time.get_ticks()#毫秒
        left_time = total_time * 60000 - taken_time#毫秒
        time_min = str(left_time // 60000)
        time_sec = str(left_time % 60000  // 1000)
        time_text = time_min.zfill(2) + ":" +time_sec.zfill(2)


        font = pygame.font.SysFont('SimHei', 20)
        is_fail = 0
        text1 = u"时间: {}".format(time_text)
        print_text(ck, font, 500, 10, text1)
        #coding=utf-8
        text2 = u"分数: {}".format(分数)    
        print_text(ck, font, 500, 30, text2)



        #计算命中率
        if acc[1] != 0:
           acc_text = str(acc[0]*100/acc[1])+ '%'
        else:
           acc_text = '0'+'%'
        text3 = u"命中率: {}".format(acc_text)


        #判断输赢
        font1 = pygame.font.SysFont('SimHei', 30)
        if left_grennbar <= 0:
            ck.blit(lose,(0,0))
            ck.blit(beginner,(40,350))
            ck.blit(shibai,(500,350))
            print_text(ck, font1, 480, 10, text3)
            print_text(ck, font1, 10, 10, text2)
            running = False
        elif left_time <= 0:
            ck.blit(win,(0,0))
            ck.blit(beginner,(40,350))
            ck.blit(shibai,(500,350))
            print_text(ck, font1, 480, 10, text3)
            print_text(ck, font1, 10, 10, text2)
            running = False



        #刷新屏幕

        pygame.display.update()
        n1 = True
    while n1:
        clock.tick(30)
        start_ck.blit(win,(0,0))
        font = pygame.font.SysFont('开始', 20)
        is_fail = 0
        text1 = u"时间: {}".format(time_text)
        print_text(ck, font, 500, 10, text1)
        #coding=utf-8
        text2 = u"分数: {}".format(分数)    
        print_text(ck, font, 500, 30, text2)
        print_text(ck, font1, 480, 10, text3)
        print_text(ck, font1, 10, 10, text2)
        buttons = pygame.mouse.get_pressed()
        x1, y1 = pygame.mouse.get_pos()
        if x1 >= 227 and x1 <= 555 and y1 >= 261 and y1 <=327:
            start_ck.blit(i44, (40,350))
            start_ck.blit(i55, (500,350))
            if buttons[0]:
                n1 = False

        elif x1 >= 227 and x1 <= 555 and y1 >= 381 and y1 <=447:
            start_ck.blit(i55, (500,350))
            start_ck.blit(i44, (40,350))
            if buttons[0]:
                pygame.quit()
                exit()

        elif x1 >= 350 and x1 <= 555 and y1 >= 560 and y1 <=599:
            start_ck.blit(i33, (230, 480))
        else:
            start_ck.blit(i4, (40,350))
            start_ck.blit(i5, (500,350))
            start_ck.blit(i3, (230, 480))


        ck.blit(start_ck,(0,0))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                exit(0)

run()
